//
//  DangQiViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/26.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "DangQiViewController.h"
#import <JTCalendar.h>
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "AddDangQiViewController.h"
#import "DangQiViewModel.h"

@interface DangQiViewController ()<JTCalendarDataSource,AddDangQiViewControllerDelegate>{
    NSMutableDictionary  *eventsByDate;
}


@property (weak, nonatomic) IBOutlet JTCalendarMenuView *calendarMenuView;
@property (weak, nonatomic) IBOutlet JTCalendarContentView *calendarContentView;
@property (weak, nonatomic) IBOutlet UIButton *addEvent;
@property (nonatomic ,strong) DangQiViewModel *viewModel;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarContentViewHeight;
@property (strong, nonatomic) JTCalendar *calendar;
- (IBAction)disMissSelf:(id)sender;



@end

@implementation DangQiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _addEvent.layer.cornerRadius = 5;
    _addEvent.layer.masksToBounds = YES;
    
  
    
    self.calendar = [JTCalendar new];
    
    // All modifications on calendarAppearance have to be done before setMenuMonthsView and setContentView
    // Or you will have to call reloadAppearance
    {
        self.calendar.calendarAppearance.calendar.firstWeekday = 2; // Sunday == 1, Saturday == 7
        self.calendar.calendarAppearance.dayCircleRatio = 9. / 10.;
        self.calendar.calendarAppearance.ratioContentMenu = 2.;
        self.calendar.calendarAppearance.focusSelectedDayChangeMode = YES;
        
        // Customize the text for each month
        self.calendar.calendarAppearance.monthBlock = ^NSString *(NSDate *date, JTCalendar *jt_calendar){
            NSCalendar *calendar = jt_calendar.calendarAppearance.calendar;
            NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:date];
            NSInteger currentMonthIndex = comps.month;
            
            static NSDateFormatter *dateFormatter;
            if(!dateFormatter){
                dateFormatter = [NSDateFormatter new];
                dateFormatter.timeZone =[NSTimeZone systemTimeZone];
            }
            
            while(currentMonthIndex <= 0){
                currentMonthIndex += 12;
            }
            NSLocale *zh_Locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"];
            [dateFormatter setLocale:zh_Locale];
            NSString *monthText = [[dateFormatter standaloneMonthSymbols][currentMonthIndex - 1] capitalizedString];
            
            return [NSString stringWithFormat:@"%ld\n%@", (long)comps.year, monthText];
        };
    }
    
    [self.calendar setMenuMonthsView:self.calendarMenuView];
    [self.calendar setContentView:self.calendarContentView];
    [self.calendar setDataSource:self];
    
    self.calendar.calendarAppearance.dayDotColor = [UIColor redColor];
    self.calendar.calendarAppearance.dayDotColorOtherMonth = [UIColor redColor];
    [self createRandomEvents];
    
    @weakify(self);
    [[[_addEvent rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        
        AddDangQiViewController *addDangQi = [[AddDangQiViewController alloc] initWithNibName:NSStringFromClass([AddDangQiViewController class]) bundle:nil];
        addDangQi.delegate = self;
        addDangQi.titleText = @"添加档期";
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSDate *date = [NSDate date];
        
        NSTimeZone *zone =[NSTimeZone systemTimeZone];
        dateFormatter.timeZone = zone;
        
        addDangQi.beinTimeText = [dateFormatter stringFromDate:date];
        
        addDangQi.endTimeText = [dateFormatter stringFromDate:date];
        [self presentViewController:addDangQi animated:YES completion:nil];
        
    }];
    _viewModel = [[DangQiViewModel alloc] init];
    [[RACObserve(_viewModel, hasLoaded) subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        [self viewDidAppear:YES];
        
    }];
    if ([_username length]==0) {
        [_viewModel fetchDataForUser:nil];
    
        
    }else{
        [_viewModel fetchDataForUser:_username];
        _addEvent.hidden = YES;
    }
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.calendar reloadData]; // Must be call in viewDidAppear
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - JTCalendarDataSource

- (BOOL)calendarHaveEvent:(JTCalendar *)calendar date:(NSDate *)date
{
   return [_viewModel validateDate:date];
}

- (void)calendarDidDateSelected:(JTCalendar *)calendar date:(NSDate *)date
{
    
    
    if ([_username length] >0) {
        return;
    }
    
    //点击 查看编辑日历
    AddDangQiViewController *addDangQi = [[AddDangQiViewController alloc] initWithNibName:NSStringFromClass([AddDangQiViewController class]) bundle:nil];
    addDangQi.delegate =self;
    if ([_viewModel validateDate:date]) {
        addDangQi.titleText = @"编辑档期";
        addDangQi.saveButtonTitle = @"确认修改";
        
        
        NSDictionary *dic = [_viewModel dicForDate:date];
        addDangQi.beinTimeText = [dic objectForKey:@"beginTime"];
        
        addDangQi.endTimeText = [dic objectForKey:@"endTime"];
        addDangQi.noteText = [dic objectForKey:@"note"];
        addDangQi.pk = [dic objectForKey:@"pk"];
        
        
    }else{
        addDangQi.titleText = @"添加档期";
        addDangQi.saveButtonTitle = @"添加";
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        
                        
        addDangQi.beinTimeText = [dateFormatter stringFromDate:date];
        
        addDangQi.endTimeText = [dateFormatter stringFromDate:date];
        addDangQi.noteText = @"";
        
    
    }
    
    [self presentViewController:addDangQi animated:YES completion:nil];

}

- (void)calendarDidLoadPreviousPage
{
//    NSLog(@"Previous page loaded");
}

- (void)calendarDidLoadNextPage
{
//    NSLog(@"Next page loaded");
}

#pragma mark - Transition examples

//- (void)transitionExample
//{
//    CGFloat newHeight = 300;
//    if(self.calendar.calendarAppearance.isWeekMode){
//        newHeight = 75.;
//    }
//    
//    [UIView animateWithDuration:.5
//                     animations:^{
//                         self.calendarContentViewHeight.constant = newHeight;
//                         [self.view layoutIfNeeded];
//                     }];
//    
//    [UIView animateWithDuration:.25
//                     animations:^{
//                         self.calendarContentView.layer.opacity = 0;
//                     }
//                     completion:^(BOOL finished) {
//                         [self.calendar reloadAppearance];
//                         
//                         [UIView animateWithDuration:.25
//                                          animations:^{
//                                              self.calendarContentView.layer.opacity = 1;
//                                          }];
//                     }];
//}

#pragma mark - Fake data

- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        NSTimeZone *zone =[NSTimeZone systemTimeZone];
        dateFormatter.timeZone = zone;
    }
    
    return dateFormatter;
}

- (void)createRandomEvents
{
    eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!eventsByDate[key]){
            eventsByDate[key] = [NSMutableArray new];
        }
        
        [eventsByDate[key] addObject:randomDate];
    }
}


- (void)disMissSelf:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)addDangQiViewController:(AddDangQiViewController *)addViewController updateSchedule:(NSString *)pk beginTime:(NSString *)beginTime endTime:(NSString *)endTime note:(NSString *)note{

    [_viewModel updateSchedule:pk note:note beginTime:beginTime endTime:endTime];
    [_viewModel fetchDataForUser:nil];
    
    [addViewController dismissViewControllerAnimated:YES completion:nil];

}
@end
